<script setup lang="ts">
import type { FormInstance, MessageBoxData } from 'element-plus'
import {
  type _IndicatorRule,
  editStateIdentity,
} from '../../'
import { DEFAULT_DATA } from './'
import { alarmApi } from '@/api'
import type { AlarmSaveOrUpdateWarningRuleParamsItem } from '@/types'

defineOptions({ name: 'SettingPanel' })

const props = withDefaults(
  defineProps<{
    title?: string
    monitorType?: _IndicatorRule['monitorType']
    timeType?: _IndicatorRule['timeType']
    data?: AlarmSaveOrUpdateWarningRuleParamsItem[]
    indicatorInfo?: any
    unit?: string
  }>(),
  {
    title: '',
    monitorType: 0,
    timeType: null,
    data: () => [],
    indicatorInfo: () => ({} as never),
    unit: '-',
  },
)
// 注入状态控制
const setIsEdit = inject<(v: boolean) => void>(
  editStateIdentity,
)
// ------------------use------------------
// #region
const { $confirm, $message } = useCurrentInstance()
const [generalWarningData, setGeneralWarningData]
  = useState({
    ...DEFAULT_DATA,
  })
const [seriousWarningData, setSeriousWarningData]
  = useState({
    ...DEFAULT_DATA,
  })
const [urgentWarningData, setUrgentWarningData] = useState({
  ...DEFAULT_DATA,
})
/** 一般告警 */
const [isGeneralWarning, setIsGeneralWarning] = useState(0)
/** 严重告警 */
const [isSeriousWarning, setIsSeriousWarning] = useState(0)
/** 紧急告警 */
const [isUrgentWarning, setIsUrgentWarning] = useState(0)
// #endregion
// ------------------静态变量------------------
// #region
const generaFormRules = generateCurrencyFormRules(
  DEFAULT_DATA,
  ['monitorType', 'warningType'],
  {
    thresholdValueDown: [
      {
        validator: (_: any, value: any, callback: any) => {
          // console.warn(isValid(1));

          const { thresholdValueDown: a } = toValue(
            seriousWarningData,
          )
          const { thresholdValueDown: b } = toValue(
            urgentWarningData,
          )
          const { thresholdValueUp } = toValue(
            generalWarningData,
          )
          if (value > thresholdValueUp) {
            callback(new Error('下限值不能大于下限值'))
          }
          else if (value < a) {
            if (isSeriousWarning.value) {
              callback(
                new Error('下限值不能小于严重告警下限值'),
              )
            }
            else {
              callback()
            }
          }
          else if (value < b) {
            if (isUrgentWarning.value) {
              callback(
                new Error('下限值不能小于紧急告警下限值'),
              )
            }
            else {
              callback()
            }
          }
          else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
    thresholdValueUp: [
      {
        validator: (_: any, value: any, callback: any) => {
          const { thresholdValueUp: a } = toValue(
            seriousWarningData,
          )
          const { thresholdValueUp: b } = toValue(
            urgentWarningData,
          )
          const { thresholdValueDown } = toValue(
            generalWarningData,
          )
          if (value < thresholdValueDown) {
            callback(new Error('上限值不能小于下限值'))
          }
          else if (value > a) {
            if (isSeriousWarning.value) {
              callback(
                new Error('上限值不能大于严重告警上限值'),
              )
            }
            else {
              callback()
            }
          }
          else if (value > b) {
            if (isUrgentWarning.value) {
              callback(
                new Error('上限值不能大于紧急告警上限值'),
              )
            }
            else {
              callback()
            }
          }
          else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
  },
)
const seriousFormRules = generateCurrencyFormRules(
  DEFAULT_DATA,
  ['monitorType', 'warningType'],
  {
    thresholdValueDown: [
      {
        validator: (_: any, value: any, callback: any) => {
          const { thresholdValueUp } = toValue(
            seriousWarningData,
          )
          const { thresholdValueDown: a } = toValue(
            generalWarningData,
          )
          const { thresholdValueDown: b } = toValue(
            urgentWarningData,
          )
          if (value > thresholdValueUp) {
            callback(new Error('下限值不能大于上限值'))
          }
          else if (value < b) {
            if (isUrgentWarning.value) {
              callback(
                new Error('下限值不能小于紧急告警下限值'),
              )
            }
            else {
              callback()
            }
          }
          else if (value > a) {
            if (isGeneralWarning.value) {
              callback(
                new Error('下限值不能大于一般告警下限值'),
              )
            }
            else {
              callback()
            }
          }
          else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
    thresholdValueUp: [
      {
        validator: (_: any, value: any, callback: any) => {
          const { thresholdValueDown } = toValue(
            seriousWarningData,
          )
          const { thresholdValueUp: a } = toValue(
            generalWarningData,
          )
          const { thresholdValueUp: b } = toValue(
            urgentWarningData,
          )
          if (value < thresholdValueDown) {
            callback(new Error('上限值不能小于下限值'))
          }
          else if (value < a) {
            if (isGeneralWarning.value) {
              callback(
                new Error('上限值不能小于一般告警上限值'),
              )
            }
            else {
              callback()
            }
          }
          else if (value > b) {
            if (isUrgentWarning.value) {
              callback(
                new Error('上限值不能大于紧急告警上限值'),
              )
            }
            else {
              callback()
            }
          }
          else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
  },
)
const urgentFormRules = generateCurrencyFormRules(
  DEFAULT_DATA,
  ['monitorType', 'warningType'],
  {
    thresholdValueDown: [
      {
        validator: (_: any, value: any, callback: any) => {
          const { thresholdValueUp } = toValue(
            urgentWarningData,
          )
          const { thresholdValueDown: a } = toValue(
            seriousWarningData,
          )
          const { thresholdValueDown: b } = toValue(
            generalWarningData,
          )
          if (value > thresholdValueUp) {
            callback(new Error('下限值不能大于下限值'))
          }
          else if (value > a) {
            if (isSeriousWarning.value) {
              callback(
                new Error('下限值不能大于严重告警下限值'),
              )
            }
            else {
              callback()
            }
          }
          else if (value > b) {
            if (isGeneralWarning.value) {
              callback(
                new Error('下限值不能大于一般告警下限值'),
              )
            }
            else {
              callback()
            }
          }
          else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
    thresholdValueUp: [
      {
        validator: (_: any, value: any, callback: any) => {
          const { thresholdValueDown } = toValue(
            urgentWarningData,
          )
          const { thresholdValueUp: a } = toValue(
            seriousWarningData,
          )
          const { thresholdValueUp: b } = toValue(
            generalWarningData,
          )
          if (value < thresholdValueDown) {
            callback(new Error('上限值不能小于下限值'))
          }
          else if (value < a) {
            if (isSeriousWarning.value) {
              callback(
                new Error('上限值不能小于严重告警上限值'),
              )
            }
            else {
              callback()
            }
          }
          else if (value < b) {
            if (isSeriousWarning.value) {
              callback(
                new Error('上限值不能小于一般告警上限值'),
              )
            }
            else {
              callback()
            }
          }
          else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
  },
)
// function isValid(index: 1 | 2 | 3) {
//   const listUp = [];
//   const listDown = [];
//   let count = 0;
//   if (isGeneralWarning.value) {
//     count++;
//     const { thresholdValueDown, thresholdValueUp } =
//       toValue(generalWarningData);
//     const a = {
//       label: '一般a',
//       value: thresholdValueDown
//     };
//     const b = {
//       label: '一般b',
//       value: thresholdValueUp
//     };
//     listUp.push(a);
//     listDown.push(b);
//   }
//   if (isSeriousWarning.value) {
//     count++;
//     const { thresholdValueDown, thresholdValueUp } =
//       toValue(seriousWarningData);
//     const a = {
//       label: '严重a',
//       value: thresholdValueDown
//     };
//     const b = {
//       label: '严重b',
//       value: thresholdValueUp
//     };
//     listUp.push(a);
//     listDown.push(b);
//   }
//   if (isUrgentWarning.value) {
//     count++;
//     const { thresholdValueDown, thresholdValueUp } =
//       toValue(seriousWarningData);
//     const a = {
//       label: '紧急a',
//       value: thresholdValueDown
//     };
//     const b = {
//       label: '紧急b',
//       value: thresholdValueUp
//     };
//     listUp.push(a);
//     listDown.push(b);
//   }
//   // const _index = count - index;
//   // const target = [list[_index], list[_index + 1]] as const;
//   // if (target[0]!.value > target[1]!.value) {
//   //   return `${target[0]?.label}不能大于${target[1]?.label}`;
//   // }

//   const listUpSort = listUp.sort((a, b) => {
//     return a.value - b.value;
//   });

//   const listDownSort = listDown.sort((a, b) => {
//     return a.value - b.value;
//   });
//   console.warn(listDownSort);
//   return '验证失败！';
// }
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const generalWarningRef = ref<FormInstance>()
const seriousWarningRef = ref<FormInstance>()
const urgentWarningRef = ref<FormInstance>()
// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region
// #endregion
// ------------------生命周期------------------
// #region

// #endregion
// ------------------内置方法---------------------
// #region
// #endregion
// ------------------方法---------------------
// #region
function resetFields(type: _IndicatorRule['warningType']) {
  if (type === 0) {
    generalWarningRef.value?.resetFields?.()
    return
  }
  if (type === 1) {
    seriousWarningRef.value?.resetFields?.()
    return
  }
  urgentWarningRef.value?.resetFields?.()
}
async function handleCheckboxChange(
  value: any,
  type: _IndicatorRule['warningType'],
) {
  if (!value) {
    const res: MessageBoxData = await $confirm(
      '取消勾选数据将不会保存，确定取消？',
      '警告',
      {
        type: 'warning',
      },
    )
    if (res !== 'confirm')
      return
  }
  setIsEdit?.(true)
  resetFields(type)
  if (type === 0) {
    setIsGeneralWarning(value)
    return
  }
  if (type === 1) {
    setIsSeriousWarning(value)
    return
  }
  setIsUrgentWarning(value)
}
async function init() {
  resetFields(0)
  resetFields(1)
  resetFields(2)
  await nextTick()

  const a = props.data.find(item => item.warningType === 0)

  setGeneralWarningData(
    a ?? {
      ...DEFAULT_DATA,
      warningType: 0,
      monitorType: props.monitorType,
      timeType: props.timeType,
    },
  )
  setIsGeneralWarning(+!!a)

  const b = props.data.find(item => item.warningType === 1)
  setSeriousWarningData(
    b ?? {
      ...DEFAULT_DATA,
      warningType: 1,
      monitorType: props.monitorType,
      timeType: props.timeType,
    },
  )
  setIsSeriousWarning(+!!b)

  const c = props.data.find(item => item.warningType === 2)
  setUrgentWarningData(
    c ?? {
      ...DEFAULT_DATA,
      warningType: 2,
      monitorType: props.monitorType,
      timeType: props.timeType,
    },
  )
  setIsUrgentWarning(+!!c)
}
function getData() {
  const data: _IndicatorRule[] = []
  if (isGeneralWarning.value)
    data.push(generalWarningData.value)
  if (isSeriousWarning.value)
    data.push(seriousWarningData.value)
  if (isUrgentWarning.value)
    data.push(urgentWarningData.value)
  return JSON.parse(
    JSON.stringify(data),
  ) as _IndicatorRule[]
}
async function validate() {
  const v: Promise<any>[] = []
  try {
    if (isGeneralWarning.value)
      v.push(generalWarningRef.value?.validate?.()!)
    if (isSeriousWarning.value)
      v.push(seriousWarningRef.value?.validate?.()!)
    if (isUrgentWarning.value)
      v.push(urgentWarningRef.value?.validate?.()!)
    const res = await Promise.all(v)
    return res.every(item => item)
  }
  catch (error) {
    console.warn(`${validate.name}:`, error)
    return false
  }
}
async function save() {
  const res = await validate()
  if (!res)
    return false
  const data = getData()
  if (data.length === 0) {
    if (props.data.length === 0) {
      $message.info('请先设置规则！')
      return false
    }
    else {
      // 解绑
      await alarmApi.deleteWarningRuleBatch([
        props.indicatorInfo.id,
      ])
      return true
    }
  }
  const params = data.map(item => ({
    ...item,
    indicatorId: props.indicatorInfo.id,
    indicatorCode: props.indicatorInfo.indicatorCode,
    statisticalType: props.indicatorInfo.statisticalType,
  }))

  // 保存
  await alarmApi.saveOrUpdateWarningRule(params)
  // console.log('表头：', params);
  // console.log('当前指标', props.indicatorInfo);
  return true
}

watchEffect(() => {
  setGeneralWarningData({
    ...unref(generalWarningData),
    timeType: props.timeType,
    monitorType: props.monitorType,
  })
  setUrgentWarningData({
    ...unref(urgentWarningData),
    timeType: props.timeType,
    monitorType: props.monitorType,
  })
  setSeriousWarningData({
    ...unref(seriousWarningData),
    timeType: props.timeType,
    monitorType: props.monitorType,
  })
})

// #endregion
defineExpose({
  getData,
  validate,
  reset: init,
  save,
})
</script>

<template>
  <div
    class="width-fill setting-panel padding-tb-sm box-border"
  >
    <p class="!margin-0 !margin-bottom-sm flex">
      <span>告警类型设置：</span>
      <span v-if="title" class="margin-left-auto">
        颗粒度：每{{ title }}
      </span>
    </p>
    <el-form
      ref="generalWarningRef"
      :model="generalWarningData"
      :rules="generaFormRules"
      label-width="100px"
    >
      <el-divider
        content-position="left"
        class="a"
        @click.stop="
          handleCheckboxChange(!isGeneralWarning, 0)
        "
      >
        <el-checkbox
          :model-value="isGeneralWarning"
          :true-value="1"
          :false-value="0"
          @click.stop="
            handleCheckboxChange(!isGeneralWarning, 0)
          "
        >
          一般
        </el-checkbox>
      </el-divider>
      <div
        class="align-center margin-bottom-sm flex justify-between gap-xs"
      >
        <el-form-item
          prop="thresholdValueDown"
          label="告警下限值:"
          class="!margin-0 flex-fillRemaining"
        >
          <el-input-number
            v-model="generalWarningData.thresholdValueDown"
            :disabled="!Boolean(isGeneralWarning)"
            controls-position="right"
            class="!width-fill free"
          />
        </el-form-item>

        <el-form-item
          label="告警上限值:"
          prop="thresholdValueUp"
          class="!margin-0 flex-fillRemaining"
        >
          <el-input-number
            v-model="generalWarningData.thresholdValueUp"
            :disabled="!Boolean(isGeneralWarning)"
            controls-position="right"
            class="!width-fill free"
          />
        </el-form-item>
        <span class="flex-incompressible">
          {{ `单位：${indicatorInfo?.unitName ?? unit}` }}
        </span>
      </div>
      <el-form-item
        prop="warningContent"
        label="告警内容:"
        class="margin-0"
      >
        <el-input
          v-model.trim="generalWarningData.warningContent"
          :disabled="!Boolean(isGeneralWarning)"
          :rows="2"
          type="textarea"
          show-word-limit
          maxlength="100"
        />
      </el-form-item>
    </el-form>
    <el-form
      ref="seriousWarningRef"
      :model="seriousWarningData"
      :rules="seriousFormRules"
      label-width="100px"
      class="margin-top"
    >
      <el-divider
        content-position="left"
        class="b"
        @click.stop="
          handleCheckboxChange(!isSeriousWarning, 1)
        "
      >
        <el-checkbox
          :model-value="isSeriousWarning"
          :true-value="1"
          :false-value="0"
          @click.stop="
            handleCheckboxChange(!isSeriousWarning, 1)
          "
        >
          严重
        </el-checkbox>
      </el-divider>
      <div
        class="align-center margin-bottom-sm flex justify-between gap-xs"
      >
        <el-form-item
          prop="thresholdValueDown"
          label="告警下限值:"
          class="!margin-0 flex-fillRemaining"
        >
          <el-input-number
            v-model="seriousWarningData.thresholdValueDown"
            :disabled="!Boolean(isSeriousWarning)"
            controls-position="right"
            class="!width-fill free"
          />
        </el-form-item>

        <el-form-item
          label="告警上限值:"
          prop="thresholdValueUp"
          class="!margin-0 flex-fillRemaining"
        >
          <el-input-number
            v-model="seriousWarningData.thresholdValueUp"
            :disabled="!Boolean(isSeriousWarning)"
            controls-position="right"
            class="!width-fill free"
          />
        </el-form-item>
        <span class="flex-incompressible">
          {{ `单位：${indicatorInfo?.unitName ?? unit}` }}
        </span>
      </div>
      <el-form-item
        prop="warningContent"
        label="告警内容:"
        class="margin-0"
      >
        <el-input
          v-model.trim="seriousWarningData.warningContent"
          :disabled="!Boolean(isSeriousWarning)"
          :rows="2"
          type="textarea"
          show-word-limit
          maxlength="100"
        />
      </el-form-item>
    </el-form>
    <el-form
      ref="urgentWarningRef"
      :model="urgentWarningData"
      :rules="urgentFormRules"
      label-width="100px"
      class="margin-top"
    >
      <el-divider
        content-position="left"
        class="c"
        @click.stop="
          handleCheckboxChange(!isUrgentWarning, 2)
        "
      >
        <el-checkbox
          :model-value="isUrgentWarning"
          :true-value="1"
          :false-value="0"
          @click.stop="
            handleCheckboxChange(!isUrgentWarning, 2)
          "
        >
          紧急
        </el-checkbox>
      </el-divider>
      <div
        class="align-center margin-bottom-sm flex justify-between gap-xs"
      >
        <el-form-item
          label="告警下限值:"
          prop="thresholdValueDown"
          class="!margin-0 flex-fillRemaining"
        >
          <el-input-number
            v-model="urgentWarningData.thresholdValueDown"
            :disabled="!Boolean(isUrgentWarning)"
            controls-position="right"
            class="!width-fill free"
          />
        </el-form-item>

        <el-form-item
          label="告警上限值:"
          prop="thresholdValueUp"
          class="!margin-0 flex-fillRemaining"
        >
          <el-input-number
            v-model="urgentWarningData.thresholdValueUp"
            :disabled="!Boolean(isUrgentWarning)"
            controls-position="right"
            class="!width-fill free"
          />
        </el-form-item>
        <span class="flex-incompressible">
          {{ `单位：${indicatorInfo?.unitName ?? unit}` }}
        </span>
      </div>
      <el-form-item
        prop="warningContent"
        label="告警内容:"
        class="margin-0"
      >
        <el-input
          v-model.trim="urgentWarningData.warningContent"
          :disabled="!Boolean(isUrgentWarning)"
          :rows="2"
          type="textarea"
          show-word-limit
          maxlength="100"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
.setting-panel {
  font-size: 14px;
  min-width: 600px;
  p {
    color: var(--el-text-color-regular);
  }
  .el-input-number {
    min-width: 150px;
  }
  .el-divider {
    position: relative;
    cursor: pointer;
    z-index: 1;
    &::after {
      content: '';
      position: absolute;
      z-index: 0;
      top: 50%;
      left: 0px;
      transform: translateY(-50%);
      height: 30px;
      width: 100%;
      background-color: transparent;
    }
  }
  .el-divider.a {
    color: var(--el-color-primary);
    background-color: currentColor;
  }
  .el-divider.b {
    color: var(--el-color-warning);
    background-color: currentColor;
    .el-checkbox {
      --el-checkbox-checked-text-color: var(
        --el-color-warning
      );
      --el-checkbox-checked-input-border-color: var(
        --el-color-warning
      );
      --el-checkbox-checked-bg-color: var(
        --el-color-warning
      );
      --el-checkbox-input-border-color-hover: var(
        --el-color-warning
      );
    }
  }
  .el-divider.c {
    color: var(--el-color-danger);
    background-color: currentColor;
    .el-checkbox {
      --el-checkbox-checked-text-color: var(
        --el-color-danger
      );
      --el-checkbox-checked-input-border-color: var(
        --el-color-danger
      );
      --el-checkbox-checked-bg-color: var(
        --el-color-danger
      );
      --el-checkbox-input-border-color-hover: var(
        --el-color-danger
      );
    }
  }
}
//-------------样式穿透-------------
</style>
